package cn.tuling.aop;

import cn.tuling.service.OrderService;
import cn.tuling.service.OrderServiceImpl;
import cn.tuling.service.UserService;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.aop.framework.ProxyFactory;

public class ProxyFactoryTest {
    public static void main(String[] args) {

        testCglib();
        System.out.println("------");
        testJdkDynamic();
    }

    public static void testJdkDynamic() {
        OrderService target = new OrderServiceImpl();

        ProxyFactory proxyFactory = new ProxyFactory();
        proxyFactory.setInterfaces(OrderService.class);
        proxyFactory.setTarget(target);
        proxyFactory.addAdvice(new MethodInterceptor() {
            @Override
            public Object invoke(MethodInvocation invocation) throws Throwable {
                System.out.println("before...");
                Object result = invocation.proceed();
                System.out.println("after...");
                return result;
            }
        });

        OrderService proxy = (OrderService) proxyFactory.getProxy();
        proxy.test();
    }

    public static void testCglib() {
        UserService target = new UserService();

        ProxyFactory proxyFactory = new ProxyFactory();
        proxyFactory.setTarget(target);
        proxyFactory.addAdvice(new MethodInterceptor() {
            @Override
            public Object invoke(MethodInvocation invocation) throws Throwable {
                System.out.println("before...");
                Object result = invocation.proceed();
                System.out.println("after...");
                return result;
            }
        });

        UserService proxy = (UserService) proxyFactory.getProxy();
        proxy.test();
    }
}
